package com.dycx.message.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.dycx.common.RestResponse;
import com.dycx.common.dto.FieldsDTO;
import com.dycx.common.vendor.weixin.WxUtils;
import com.dycx.message.entity.MessageRecordDO;
import com.dycx.message.entity.MessageTaskDO;
import com.dycx.message.entity.TemplateDO;
import com.dycx.message.service.MessageRecordService;
import com.dycx.message.service.MessageService;
import com.dycx.message.service.MessageTaskService;
import com.dycx.message.service.TemplateService;
import com.dycx.message.vendor.MessageApi;
import com.dycx.message.vendor.dto.MessageContentDTO;
import com.dycx.message.vendor.dto.RecipientDTO;
import com.dycx.message.vendor.dto.RequestDTO;
import com.dycx.message.vendor.weixin.mp.feign.MpFeignClient;
import com.dycx.message.vendor.weixin.mp.feign.vo.OpenidListVO;
import com.dycx.message.vendor.weixin.mp.feign.vo.UserListResultVO;
import com.dycx.message.vo.TemplateVO;
import com.dycx.system.service.ConfigService;
import com.dycx.system.vo.SystemConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
@AllArgsConstructor
public class MessageImpl implements MessageService {

    private MessageTaskService templateTaskService;
    private TemplateService templateService;
    private MpFeignClient mpFeignClient;
    private ConfigService configService;

    /**
     * 发送消息
     *
     * @param recipient      接收人
     * @param messageTaskId  模版id
     * @param messageContent 消息内容
     * @return
     */

    @Override
    public RestResponse<String> sendMessage(int messageTaskId, RecipientDTO recipient, MessageContentDTO messageContent) {
        return sendMessage(messageTaskId, recipient, messageContent, "");
    }

    @Override
    public RestResponse<String> sendMessage(int messageTaskId, RecipientDTO recipient, MessageContentDTO messageContent, String url) {
        if (ObjectUtil.isEmpty(recipient)) throw new RuntimeException("接收人不能为空");
        if (ObjectUtil.isEmpty(messageTaskId)) throw new RuntimeException("任务id不能为空");
        if (ObjectUtil.isEmpty(messageContent)) throw new RuntimeException("消息内容不能为空");

        //查询任务
        MessageTaskDO messageTaskDO = templateTaskService.getById(messageTaskId);
        if (ObjectUtil.isEmpty(messageTaskDO)) throw new RuntimeException("未查询到任务信息");
        if (ObjectUtil.isEmpty(messageTaskDO.getTemplateIds()))
            throw new RuntimeException("消息模版未设置");

        List<TemplateVO> templateList = templateService.getListByIds(messageTaskDO.getTemplateIds());

        if (ObjectUtil.isEmpty(templateList)) throw new RuntimeException("没有有效的消息模版");

        RestResponse<String> res = RestResponse.success();

        for (TemplateVO item : templateList) {
            List<FieldsDTO> templateParam = MessageApi.setParamsValue(item.getFields(), messageContent, item.getMessageType());

            //日志数据
            MessageRecordDO messageRecordDO = new MessageRecordDO();
            messageRecordDO.setTaskId(messageTaskId);
            messageRecordDO.setTaskName(messageTaskDO.getTaskName());
            messageRecordDO.setTemplateId(item.getId());
            messageRecordDO.setTemplateName(item.getName());
            messageRecordDO.setTemplateCode(item.getCode());
            messageRecordDO.setTemplateData(JSON.toJSONString(item.getFields()));
            messageRecordDO.setTemplateContent(item.getContent());
            messageRecordDO.setMessageType(item.getMessageType());
            messageRecordDO.setMessageData(JSON.toJSONString(templateParam));

            RequestDTO requestDTO = new RequestDTO();
            requestDTO.setRecipient(recipient);
            requestDTO.setMessageType(item.getMessageType());
            requestDTO.setTemplateCode(item.getCode());
            requestDTO.setTemplateParam(templateParam);
            requestDTO.setUrl(url);
            requestDTO.setMessageRecordDO(messageRecordDO);

            RestResponse<String> result = MessageApi.sendMessage(requestDTO);
            if (!result.isSuccess()) {
                res = result;
            }
        }

        return res;
    }


    @Override
    public Boolean sendWxTemplateMessage(int templateId, MessageContentDTO messageContent) {
        SystemConfig config = configService.getSystemConfig();
        String accessToken = WxUtils.getAccessToken(config.getTemplateMessageWxMpAppId(), config.getTemplateMessageWxMpAppSecret());

        TemplateDO templateDO = templateService.getById(templateId);

        sendWxTemplateMessage(10000, "", accessToken, templateDO, messageContent, "http://" + config.getDomain());
        return true;
    }

    private void sendWxTemplateMessage(Integer index, String nextOpenid, String accessToken, TemplateDO templateDO, MessageContentDTO messageContent, String url) {
        UserListResultVO vo = mpFeignClient.getUserList(accessToken, nextOpenid);

//        MessageRecordDO testDO = new MessageRecordDO();
//        testDO.setRecipient("11111111111111");
//        testDO.setResult(true);
//        testDO.setMessageData(JSON.toJSONString(vo));
//        testDO.setResultDescription(nextOpenid);
//        messageRecordService.save(testDO);

//        //测试start
//        List<String> openids = new ArrayList<>();
//        openids.add("ozyBG6_dp-QiQIFPgtj6rr4AhWSk");
//        OpenidListVO openidListVO = new OpenidListVO();
//        openidListVO.setOpenid(openids);
//        UserListResultVO vo = new UserListResultVO();
//        vo.setCount(1);
//        vo.setNextOpenid("");
//        vo.setTotal(1);
//        vo.setData(openidListVO);
//        //测试end

//        UserListResultVO vo = new UserListResultVO();
//        List<String> openIds = new ArrayList<>();
//        for (int i = 1; i < 10000; i++) {
//            openIds.add(i+"---aaaaaa");
//        }
//        OpenidListVO openidListVO = new OpenidListVO();
//        openidListVO.setOpenid(openIds);
//        vo.setData(openidListVO);

        RecipientDTO recipient = new RecipientDTO();
        recipient.setWxMpOpenId(vo.getData().getOpenid());

        List<FieldsDTO> templateParam = MessageApi.setParamsValue(templateDO.getFields(), messageContent, templateDO.getMessageType());

        //日志数据
        MessageRecordDO messageRecordDO = new MessageRecordDO();
        messageRecordDO.setTemplateId(templateDO.getId());
        messageRecordDO.setTemplateName(templateDO.getName());
        messageRecordDO.setTemplateCode(templateDO.getCode());
        messageRecordDO.setTemplateData(JSON.toJSONString(templateDO.getFields()));
        messageRecordDO.setTemplateContent(templateDO.getContent());
        messageRecordDO.setMessageType(templateDO.getMessageType());
        messageRecordDO.setMessageData(JSON.toJSONString(templateParam));

        RequestDTO requestDTO = new RequestDTO();
        requestDTO.setRecipient(recipient);
        requestDTO.setMessageType(templateDO.getMessageType());
        requestDTO.setTemplateCode(templateDO.getCode());
        requestDTO.setTemplateParam(templateParam);
        requestDTO.setUrl(url);
        requestDTO.setMessageRecordDO(messageRecordDO);

        MessageApi.sendMessage(requestDTO);


        if (vo.getTotal() > index) {
            index = index + 10000;
            sendWxTemplateMessage(index, vo.getNextOpenid(), accessToken, templateDO, messageContent, url);
        }
    }

}
